<?php

namespace app\admin\controller;

use Alipay\EasySDK\Kernel\Factory as alipayFactory;
use app\admin\model\User;
use app\common\controller\Backend;
use EasyWeChat\Factory;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Db;
use think\Model;

/**
 * 续租订单管理
 *
 * @icon fa fa-circle-o
 */
class OrderContinue extends Backend
{
    
    /**
     * OrderContinue模型对象
     * @var \app\admin\model\OrderContinue
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $order_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\OrderContinue;
        $statusList = \app\admin\model\OrderContinue::fetchStatus();
        $payTypeList = \app\admin\model\OrderContinue::fetchPayType();
        $cancelReasonList = \app\admin\model\OrderContinue::fetchCancelReason();
        $merchantCarInsure = \app\admin\model\MerchantCarInsure::getList();
        $continueStatusList = \app\admin\model\OrderContinue::fetchContinueStatus();
//        dump($merchantCarInsure);die;
        $this->view->assign(['statusList' => $statusList, 'payTypeList' => $payTypeList, 'cancelReasonList' => $cancelReasonList, 'merchantCarInsure' => $merchantCarInsure, 'continueStatusList' => $continueStatusList]);
        $this->assignconfig(['statusList' => $statusList, 'payTypeList' => $payTypeList, 'cancelReasonList' => $cancelReasonList, 'merchantCarInsure' => $merchantCarInsure, 'continueStatusList' => $continueStatusList]);
        $order_id = $this->request->param('order_id');
        $this->order_id = $order_id;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看.
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $builder = $this->model->withJoin(['user', 'merchant_car', 'order'])
                ->where($where)
                ->where('order_continue.is_delete', 1);
            if($this->order_id){
                $builder->where('order_continue.order_id', $this->order_id);
            }
            $total = $builder
                ->order($sort, $order)
                ->count();
            $list  = $builder
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key=>$value){
                $list[$key]['time_slot'] = date('Y-m-d H:i:s', $value->start_time) .'~'.date('Y-m-d H:i:s', $value->end_time);
            }
            $result = ['total' => $total, 'rows' => $list];

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $order = \app\admin\model\Order::where(['is_delete' => 1, 'id' => $this->order_id])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        if($order['status'] != 2){
            $text = \app\admin\model\Order::fetchStatus($order['status']);
            $this->error('订单'.$text);
        }
        if($order['continue_status'] == 2 || $order['continue_status'] == 3){
            $this->error('订单已续租');
        }
        $merchant_car = \app\admin\model\MerchantCar::with('cars')->where(['is_delete' => 1, 'id' => $order['merchant_car_id']])->find();
//        dump($merchant_car->toArray());die;
        if(!$merchant_car){
            $this->error('商家车辆不存在');
        }
        if($merchant_car['status'] == 2){
            $this->error('商家车辆已下架');
        }
        //订单续租订单
        $order_continue = \app\admin\model\OrderContinue::where(['is_delete' => 1, 'order_id' => $order['id']])->where('pay_status', 'in', '1,2')->order('end_time', 'desc')->select();
        $status_list = $order_continue->column('pay_status');
        if(in_array(1, $status_list)){
            $this->error('该订单已有待支付的续租订单');
        }
        $end_time_list = $order_continue->column('end_time');
        if($end_time_list){
            $order['end_time'] = $end_time_list[0];
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'add' : $name)->check($params);
                    }
                    if(strtotime($params['end_time']) < strtotime($order['end_time'])){
                        $this->error('结束日期错误');
                    }
                    $last_end_time = $this->model->where(['is_delete' => 1, 'user_id' => $order['user_id'], 'order_id' => $order['id']])->where('pay_status', 'in', '1,2,4')->order('createtime', 'desc')->value('end_time');
                    if($last_end_time && strtotime($params['end_time']) < $last_end_time){
                        return ['status' => 0, 'message' => '结束时间不能小于该订单最后一次续租时间', 'result' => ''];
                    }
                    $last_time = strtotime("-1 month");
                    //临时下架时间
                    $merchant_car_time = \app\admin\model\MerchantCarTime::where(['is_delete' => 1, 'merchant_car_id' => $order['merchant_car_id']])->where('end_time', '>', $last_time)->select();
                    foreach ($merchant_car_time as $ke=>$vl){
                        $is_time_cross = is_time_cross($vl['start_time'], $vl['end_time'], strtotime($params['start_time']), strtotime($params['end_time']));
                        if($is_time_cross){
                            $this->error('租赁时间段内商家车辆会临时下架');
                        }
                    }
                    $car_price = $merchant_car['car_price'];
                    $rental_money = 0;
                    //商家车辆远期价格
                    $merchant_car_price = \app\admin\model\MerchantCarPrice::where(['is_delete' => 1, 'merchant_car_id' => $order['id']])->where('end_time', '>', $last_time)->select()->toArray();
                    $days = 0;
                    if($merchant_car_price){
                        $date_list = createDateRange($params['start_time'], $params['end_time']);
                        $new_date_list = [];
                        foreach ($date_list as $key=>$value){
                            $new_date_list[$value] = $car_price;
                            foreach ($merchant_car_price as $kk=>$vv){
                                if(strtotime($value) >= $vv['start_time'] && strtotime($value) <= $vv['end_time']){
                                    $new_date_list[$value] = $vv['price'];
                                }
                            }
                        }
                        $days = count($date_list);
                        $rental_money = array_sum($new_date_list);
                    }else{
                        //天数
                        $days = ceil(bcdiv(bcsub(strtotime($params['end_time']), strtotime($params['start_time']), 0), 86400, 2));
                        $rental_money = bcmul($order['price'], $days, 2);
                    }
                    //保险
                    $merchant_insure = \app\admin\model\MerchantCarInsure::where('id', $params['insurance_id'])->find();
                    $insurance = $merchant_insure['price']??0;
                    //押金
                    $car_deposit = 0;
//                    if($order['deposit_type'] == 2){
//                        //走第三方免押接口判断
//
//                    }else{
//                        $car_deposit = $merchant_car['car_deposit']??0;
//                    }
                    //判断取还车是否夜间
                    $merchant = \app\admin\model\Merchant::where('id', $order['merchant_id'])->find();
                    $night_time = explode('-', $merchant['night_time']);
                    $night_hour_list = getHours($night_time[0], $night_time[1]);
                    $end_hour = date('H', $params['end_time']);
                    $night_return_fee = 0;
                    if(in_array($end_hour, $night_hour_list)){
                        $night_return_fee = $merchant_car['night_return_fee'];
                    }
                    $all_money = bcadd($rental_money, ($night_return_fee + $insurance), 2);

                    $params['start_time'] = strtotime($params['start_time']);
                    $params['end_time'] = strtotime($params['end_time']);
                    $params['order_id'] = $order['id'];
                    $params['user_id'] = $order['user_id'];
                    $params['merchant_id'] = $order['merchant_id'];
                    $params['merchant_car_id'] = $order['merchant_car_id'];
                    $params['out_trade_no'] = \app\admin\model\OrderContinue::getOutTradeNo();
                    $params['days'] = $days;
                    $params['price'] = $car_price;
                    $params['handle_fee'] = 0;
                    $params['night_return_fee'] = $night_return_fee;
                    $params['rental_money'] = $rental_money;
                    $params['deposit'] = $car_deposit;
                    $params['deposit_status'] = $car_deposit > 0 ? 1 : 0;
                    $params['rental_money'] = $rental_money;
                    $params['insurance'] = $insurance;
                    $params['all_money'] = $all_money;
                    $params['send_type'] = $order['send_type'];
                    $params['pay_type'] = $order['pay_type'];
                    $params['continue_status'] = 2;
                    $params['createtime'] = time();
                    $params['last_all_money'] = $all_money;
                    $result = $this->model->save($params);
                    \app\common\model\Order::where('id', $order['id'])->update(['continue_status' => 3]);
                    \app\common\model\Order::where('id', $order['id'])->inc('continue_num', 1)->update();
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign('order', $order);
        $this->view->assign('merchant_car', $merchant_car);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $order = \app\admin\model\Order::where(['is_delete' => 1, 'id' => $this->order_id])->find();
        if(!$order){
            $this->error('订单不存在');
        }
        $merchant_car = \app\admin\model\MerchantCar::with('cars')->where(['is_delete' => 1, 'id' => $order['merchant_car_id']])->find();
        if(!$merchant_car){
            $this->error('商家车辆不存在');
        }
        if($merchant_car['status'] == 2){
            $this->error('商家车辆已下架');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'add' : $name)->check($params);
                    }
                    if(strtotime($order['end_time']) < strtotime(strtotime($order['start_time']))){
                        $this->error('结束日期错误');
                    }
                    $last_time = strtotime("-1 month");
                    //临时下架时间
                    $merchant_car_time = \app\admin\model\MerchantCarTime::where(['is_delete' => 1])->where('end_time', '>', $last_time)->select();
                    foreach ($merchant_car_time as $ke=>$vl){
                        $is_time_cross = is_time_cross($vl['start_time'], $vl['end_time'], strtotime($params['start_time']), strtotime($params['end_time']));
                        if($is_time_cross){
                            $this->error('租赁时间段内商家车辆会临时下架');
                        }
                    }
                    $car_price = $merchant_car['car_price'];
                    $rental_money = 0;
                    //商家车辆远期价格
                    $merchant_car_price = \app\admin\model\MerchantCarPrice::where(['is_delete' => 1, 'merchant_car_id' => $order['id']])->where('end_time', '>', $last_time)->select()->toArray();
                    $days = 0;
                    if($merchant_car_price){
                        $date_list = createDateRange($params['start_time'], $params['end_time']);
                        $new_date_list = [];
                        foreach ($date_list as $key=>$value){
                            $new_date_list[$value] = $car_price;
                            foreach ($merchant_car_price as $kk=>$vv){
                                if(strtotime($value) >= $vv['start_time'] && strtotime($value) <= $vv['end_time']){
                                    $new_date_list[$value] = $vv['price'];
                                }
                            }
                        }
                        $days = count($date_list);
                        $rental_money = array_sum($new_date_list);
                    }
                    //保险
                    $merchant_insure = \app\admin\model\MerchantCarInsure::where('id', $params['insurance_id'])->find();
                    $insurance = $merchant_insure['price']??0;
                    $all_money = bcadd($rental_money, ($merchant_car['handle_fee'] + $insurance), 2);

                    $params['id'] = $ids;
                    $params['start_time'] = strtotime($params['start_time']);
                    $params['end_time'] = strtotime($params['end_time']);
                    $params['days'] = $days;
                    $params['price'] = $car_price;
                    $params['handle_fee'] = $order['handle_fee'];
                    $params['rental_money'] = $rental_money;
                    $params['insurance'] = $insurance;
                    $params['all_money'] = $all_money;
                    $params['updatetime'] = time();
                    $result = $this->model->where('id', $ids)->update($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign('order', $order);
        $this->view->assign('merchant_car', $merchant_car);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model
            ->field('out_trade_no,user_id,merchant_id,merchant_car_id,price,start_time,end_time,days,price,rental_money,all_money,insurance_id,insurance,handle_fee,pay_type,pay_status,createtime,time_end,total_fee,cancel_time,cancel_reason,out_refund_no,refund_id,refund_time,refund_money')
            ->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if($row){
            $user = User::where('id', $row['user_id'])->find();
            $row['user_id'] = $user['username'];
            $merchant = \app\admin\model\Merchant::where('id', $row['merchant_id'])->find();
            $row['shop_name'] = $merchant['shop_name'];
            $row['shop_address'] = $merchant['province'] . $merchant['city'] . $merchant['area'] . $merchant['street'];
            $merchant_car = \app\admin\model\MerchantCar::with('cars')->where('id', $row['merchant_car_id'])->find();
            $row['car_name'] = $merchant_car['car_name'];
            $row['pay_status'] = \app\admin\model\OrderContinue::fetchStatus($row['pay_status']);
            $row['pay_type'] = \app\admin\model\OrderContinue::fetchPayType($row['pay_type']);
            $row['createtime'] = date('Y-m-d H:i:s', $row['createtime']);
            $row['time_end'] = $row['time_end'] ? date('Y-m-d H:i:s', $row['time_end']) : '';
            $row['refund_time'] = $row['refund_time'] ? date('Y-m-d H:i:s', $row['refund_time']) : '';
            $row['cancel_time'] = $row['cancel_time'] ? date('Y-m-d H:i:s', $row['cancel_time']) : '';
            $row['cancel_reason'] = $row['cancel_reason'] ? \app\admin\model\OrderContinue::fetchCancelReason($row['cancel_reason']) : '';
            $insurance = \app\admin\model\MerchantCarInsure::where('id', $row['insurance_id'])->find();
            $row['insurance_id'] = $insurance['insure_name'];
            unset($row['merchant_id'],$row['merchant_car_id']);
        }
//        dump($row);die;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where('id', 'in', $ids)->update(['is_delete' => 2, 'deletetime' => time()]);
        $this->success();
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        $ids = $this->request->param('ids');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['pay_status'] != 2 || $row['pay_status'] != 1){
            $text = \app\admin\model\OrderChange::fetchStatus($row['pay_status']);
            $this->error('订单'.$text);
        }
        if(!$this->request->isPost()){
            return $this->view->fetch();
        }
        Db::startTrans();
        try {
            $params = $this->request->post('row/a');
            $user_model = new User();
            if($row['pay_status'] == 2){
                $update = ['pay_status' => 3, 'cancel_time' => time(), 'cancel_reason' => $params['cancel_reason']];
                $out_refund_no = \app\admin\model\OrderContinue::getOutRefundNo();
                $update['out_refund_no'] = $out_refund_no;
                //退款接口
                $user = $user_model->where('id', $row['user_id'])->find();
                if($row['pay_type'] == 1){//微信退款
                    $res = $this->refund($row, $user, $row['last_all_money']);
                    if($res['return_code'] == 'SUCCESS' && $res['result_code']=='SUCCESS'){
                        $update['out_refund_no'] = $out_refund_no;
                        $update['refund_id'] = $res['refund_id'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                        $update['last_all_money'] = 0;
                        //更新订单
                        $res = $this->model->where('id', $row['id'])->update($update);
                        \app\admin\model\Order::where('id', $row['order_id'])->dec('continue_num', 1)->update();
                        if($res){
                            $platform_log = [
                                'user_id' => $row['user_id'],
                                'amount' => $row['last_all_money'],
                                'type' => 9,
                                'log_note' => '续租订单退款',
                                'order_id' => $row['id'],
                                'order_type' => 1,
                                'createtime' => time(),
                                'total_order_id' => $row['order_id']
                            ];
                            \app\common\model\PlatformLog::insert($platform_log);
                        }
                    }else{
                        Db::rollback();
                        $this->error('取消失败');
                    }
                }else{
                    $res = $this->alipayRefund($row, $user, $row['last_all_money']);
                    if($res['code'] == '10000'){
                        $update['out_refund_no'] = $out_refund_no;
                        $update['refund_id'] = $res['trade_no'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = $res['refund_fee'];
                        $update['last_all_money'] = 0;
                        //更新订单
                        $res = $this->model->where('id', $row['id'])->update($update);
                        \app\admin\model\Order::where('id', $row['order_id'])->dec('continue_num', 1)->update();
                        if($res){
                            $platform_log = [
                                'user_id' => $row['user_id'],
                                'amount' => $row['last_all_money'],
                                'type' => 9,
                                'log_note' => '续租订单退款',
                                'order_id' => $row['id'],
                                'order_type' => 1,
                                'createtime' => time(),
                                'total_order_id' => $row['order_id']
                            ];
                            \app\common\model\PlatformLog::insert($platform_log);
                        }
                    }else{
                        Db::rollback();
                        $this->error('取消失败');
                    }
                }
                //更新主订单
                $count = $this->model->where(['is_delete' => 1, 'order_id' => $row['order_id']])->where('pay_status', 'in', '1,2')->count();
                if($count == 0){
                    \app\admin\model\Order::where('id', $row['order_id'])->update(['continue_status' => 6]);
                }
            }else{
                $update = ['cancel_time' => time(), 'pay_status' => 3, 'cancel_reason' => $params['cancel_reason'], 'last_all_money' => 0];
                //更新订单
                $res = $this->model->where('id', $row['id'])->update($update);
                //更新主订单
                \app\admin\model\Order::where('id', $row['order_id'])->update(['continue_status' => 6]);
                if($row['continue_status'] == 2){
                    \app\admin\model\Order::where('id', $row['order_id'])->dec('continue_num', 1)->update();
                }
            }

            Db::commit();
            $this->success('取消订单成功！');
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 退款
     */
    public function return()
    {
        $ids = $this->request->param('ids');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['pay_status'] != 2){
            $text = \app\admin\model\OrderChange::fetchStatus($row['pay_status']);
            $this->error('订单'.$text);
        }
        if(!$this->request->isPost()){
            return $this->view->fetch();
        }
        Db::startTrans();
        try {
            $params = $this->request->post('row/a');
            if($params['refund_money'] > $row['last_all_money']){
                $this->error('超出订单剩余金额');
            }
            $user_model = new User();
            $update = ['pay_status' => 4];
            $out_refund_no = \app\admin\model\OrderContinue::getOutRefundNo();
            $update['out_refund_no'] = $out_refund_no;
            //退款接口
            $user = $user_model->where('id', $row['user_id'])->find();
            if($row['pay_type'] == 1){//微信退款
                $res = $this->refund($row, $user, $params['refund_money']);
                if($res['return_code'] == 'SUCCESS' && $res['result_code']=='SUCCESS'){
                    $update['out_refund_no'] = $out_refund_no;
                    $update['refund_id'] = $res['refund_id'];
                    $update['refund_time'] = time();
                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                    $last_all_money = bcsub($row['last_all_money'], $params['refund_money'], 2);
                    $update['last_all_money'] = $last_all_money > 0 ? $last_all_money : 0;
                    //更新订单
                    $res = $this->model->where('id', $row['id'])->update($update);
                    if($res){
                        $platform_log = [
                            'user_id' => $user['id'],
                            'amount' => $params['refund_money'],
                            'type' => 9,
                            'log_note' => '续租订单退款',
                            'order_id' => $row['id'],
                            'order_type' => 1,
                            'createtime' => time(),
                            'total_order_id' => $row['order_id']
                        ];
                        \app\common\model\PlatformLog::insert($platform_log);
                    }
                }else{
                    Db::rollback();
                    $this->error('退款失败');
                }
            }else{
                $res = $this->alipayRefund($row, $user, $params['refund_money']);
                if($res['code'] == '10000'){
                    $update['out_refund_no'] = $out_refund_no;
                    $update['refund_id'] = $res['trade_no'];
                    $update['refund_time'] = time();
                    $update['refund_money'] = $res['refund_fee'];
                    $last_all_money = bcsub($row['last_all_money'], $params['refund_money'], 2);
                    $update['last_all_money'] = $last_all_money > 0 ? $last_all_money : 0;
                    //更新订单
                    $res = $this->model->where('id', $row['id'])->update($update);
                    if($res){
                        $platform_log = [
                            'user_id' => $user['id'],
                            'amount' => $params['refund_money'],
                            'type' => 9,
                            'log_note' => '续租订单退款',
                            'order_id' => $row['id'],
                            'order_type' => 1,
                            'createtime' => time(),
                            'total_order_id' => $row['order_id']
                        ];
                        \app\common\model\PlatformLog::insert($platform_log);
                    }
                }else{
                    Db::rollback();
                    $this->error('退款失败');
                }
            }

            Db::commit();
            $this->success('退款成功！');
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 审核
     */
    public function examine()
    {
        $ids = $this->request->param('ids');
        $type = $this->request->param('type');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['pay_status'] != 1){
            $text = \app\admin\model\OrderContinue::fetchStatus($row['pay_status']);
            $this->error('订单'.$text);
        }
        if($row['continue_status'] != 1){
            $text = \app\admin\model\OrderContinue::fetchContinueStatus($row['continue_status']);
            $this->error('订单'.$text);
        }
        Db::startTrans();
        try {
            $params = $this->request->post('row/a');
            if($type == 1){//通过
                $this->model->where('id', $ids)->update(['continue_status' => 2, 'exmain_time' => time()]);
                \app\admin\model\Order::where('id', $row['order_id'])->update(['continue_status' => 3]);
                \app\admin\model\Order::where('id', $row['order_id'])->inc('continue_num', 1)->update();
            }else{//拒绝
                $this->model->where('id', $ids)->update(['continue_status' => 3, 'exmain_time' => time()]);
                \app\admin\model\Order::where('id', $row['order_id'])->update(['continue_status' => 4]);
            }

            Db::commit();
            $this->success('审核成功！');
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    //微信退款
    public function refund($order, $user, $refund_money){
        $refundFee = $refund_money*100;
        $config = Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $result = $app->refund->byOutTradeNumber($order['out_trade_no'], $order['out_refund_no'], $order['all_money']*100, $refundFee, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '订单退款',
        ]);
        return $result;
    }

    //支付宝退款
    public function alipayRefund($order, $user, $refund_money){
        $refundFee = $refund_money*100;
        alipayFactory::setOptions(getOption());
        $result = alipayFactory::payment()->common()->refund($order['out_trade_no'], $refundFee);
        if(!$result){
            return false;
        }
        if($result->code != 10000){
            return false;
            $result->msg."，".$result->sub_msg.PHP_EOL;
        }
        $return_result = json_decode($result->httpBody, true);
        return $return_result['alipay_trade_refund_response'];
    }

}
